package com.china.produce.netty.learning.client;

import com.china.produce.netty.learning.message.rpc.RpcRequestMessage;
import com.china.produce.netty.learning.protocol.MessageCodecSharable;
import com.china.produce.netty.learning.protocol.ProcotolFrameDecoder;
import com.china.produce.netty.learning.client.rpc.RpcResponseMessageHandler;
import com.china.produce.netty.learning.server.service.rpc.RpcService;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.concurrent.DefaultPromise;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2024/9/21
 */
public class RpcClient {

    private static volatile Channel channel = null;

    private static Object lock = new Object();

    //并发计数器
    private static AtomicInteger seqId = new AtomicInteger(0);

    public static void main(String[] args) {

        RpcService proxy = getProxy(RpcService.class);

        System.out.println(proxy.sayHello("chengdu"));

    }

    private static<T> T getProxy(Class<T> clazz) {

        return   (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

                RpcRequestMessage message = new RpcRequestMessage(
                        seqId.getAndIncrement(),
                        clazz.getName(),
                        method.getName(),
                        method.getReturnType(),
                        method.getParameterTypes(),
                        args
                );
                //用于其他线程与当前主线程进行通信
                final DefaultPromise<Object> promise = new DefaultPromise<>(getChannel().eventLoop());
                RpcResponseMessageHandler.promiseMap.put(message.getSequenceId(), promise);
                //远程调用（获取channel方式是通过单例模式来获取）
                getChannel().writeAndFlush(message);
                promise.await();//阻塞等待
                if (promise.isSuccess()) {
                    return promise.getNow();
                }else{
                    throw new RuntimeException((Exception)promise.getNow());
                }
            }
        });
    }


    public static Channel getChannel() {
        if (channel != null) {
            return channel;
        }
        synchronized (lock) {
            if (channel != null){
                return channel;
            }
            initChannel();//初始化channel
            return channel;
        }
    }

    private static void initChannel() {
        MessageCodecSharable messageCodec = new MessageCodecSharable();
        LoggingHandler loggingHandler = new LoggingHandler(LogLevel.DEBUG);
        RpcResponseMessageHandler responseMessageHandler = new RpcResponseMessageHandler();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap()
                .group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ProcotolFrameDecoder());
                        ch.pipeline().addLast(loggingHandler);
                        ch.pipeline().addLast(messageCodec);
                        ch.pipeline().addLast(responseMessageHandler);
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                            }
                        });
                    }
                });
        try {
            channel = bootstrap.connect("localhost", 8081).sync().channel();
            System.out.println("客户端连接成功");
            channel.closeFuture().addListener(future -> {
                worker.shutdownGracefully();
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
